const { JJUserAccount, JJUserAccountBill,Ctcdb } = require('../../models/ctcdb');
const moment = require('moment');
const WxPay = require('../../utils/wxPay');
const tools = require('../../utils/tools')

async function getAccountInfo({ userId }) {
  const account = await JJUserAccount.findOne({
    where: {
      jUserId: userId
    },
    attributes: ['balance', 'balanceCash', 'lockSum'],
    raw: true
  });
  return { account }
}

async function getAccountBill({ userId, offset, limit }) {
  const where = { userId };
  const [list, count] = await Promise.all([
    JJUserAccountBill.findAll({
      where,
      attributes: ['amount', 'userId', 'type', 'remark', 'createTime'],
      raw: true,
      offset,
      limit,
      order: [['id', 'desc']]
    }),
    JJUserAccountBill.count({ where })
  ]);
  list.map((item) => {
    item.createTime = tools.formatHHMM(item.createTime);
    return item;
  });
  return {
    list,
    count
  }
}

async function withDraw({ amount, userId }) {
  const wxPay = new WxPay();
  return new Promise((resolve, reject) => {
    wxPay.withDraw({
      partner_trade_no: "fdsafdsaf1312",
      openid: "ot9iP4rQGcL12rGDxzCCEt5GAif0",
      check_name: 'NO_CHECK',
      amount: parseInt(amount * 100),
      spbill_create_ip: '127.0.0.1',
      desc: '提现'
    }, function (err, data) {
      console.log(err)
      console.log(data)
      if (err) {
        return reject(err)
      }
      return resolve(data)
    })
  })
}

module.exports = {
  // 获取账户信息
  getAccountInfo,
  // 获取用户的账单列表
  getAccountBill,
  // 提现
  withDraw
};
